package org.example.big_event.service;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.example.big_event.mapper.ArticleMapper;
import org.example.big_event.pojo.Article;
import org.example.big_event.pojo.PageBean;
import org.example.big_event.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

@Service
public class ArticleServiceimpl implements ArticleService {

    @Autowired
    private ArticleMapper articleMapper;

    @Override
    public void add(Article article) {
        //补充其他属性值
        article.setCreateTime(LocalDateTime.now());
        article.setUpdateTime(LocalDateTime.now());
        //获取用户id
        Map<String,Object> map = ThreadLocalUtil.get();
        Integer userId = (Integer) map.get("id");
        article.setCreateUser(userId);

        articleMapper.add(article);

    }

    @Override
    public PageBean<Article> list(Integer pageNum, Integer pageSize, Integer categoryId, String state) {
    //1.创建PageBean对象
        PageBean<Article> pb = new PageBean<>();
    //2.开启分页查询 PageHelper
        PageHelper.startPage(pageNum, pageSize);
    //3.调用mapper完成分页查询
        Map<String,Object> map = ThreadLocalUtil.get();
        Integer userId = (Integer) map.get("id");
        List<Article> as = articleMapper.list(userId,categoryId,state);

    //Page中提供了方法，可以获得PageHelper分页后的总条数和当前页数据
        Page<Article> p = (Page<Article>) as;


    //把数据填充到pageBean对象中
        pb.setTotal(p.getTotal());
        pb.setItems(p.getResult());
        return pb;
    }

    @Override
    public void update(Article article) {
        article.setUpdateTime(LocalDateTime.now());
        articleMapper.update(article);
    }

    @Override
    public Article findByArticleId(Integer id) {
        Article a = articleMapper.findByArticleId(id);
        return a;
    }

    @Override
    public void delete(Integer id) {
        articleMapper.delete(id);
    }
}
